package com.googlecode.mastercrud.persistence;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.googlecode.mastercrud.persistence.annotations.DefaultOrder;

/**
 * Classe representando um critério a ser utilizado para obter dados.
 * 
 * @author Marlon Silva Carvalho
 */
public class Criterias {
	private String query;
	private Integer maxResults = 0;
	private Collection<OrderColumn> orders = new ArrayList<OrderColumn>();
	private int order;
	private Map<String, Object> parameters = new HashMap<String, Object>();
	private int firstResult = 0;
	
	public Criterias(){}

	public Criterias(String query, Integer maxResults, int order, int firstResult) {
		this.maxResults = maxResults;
		this.order = order;
		this.firstResult = firstResult;
		this.query = query;
	}

	public Criterias(Integer maxResults, int firstResult) {
		this.setMaxResults(maxResults);
		this.setFirstResult(firstResult);
	}

	public Integer getMaxResults() {
		return maxResults;
	}

	public void setMaxResults(Integer maxResults) {
		this.maxResults = maxResults;
	}

	public int getFirstResult() {
		return firstResult;
	}

	public void setFirstResult(int firstResult) {
		this.firstResult = firstResult;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public int getOrder() {
		return order;
	}

	public void setOrder(int order) {
		this.order = order;
	}

	public Map<String, Object> getParameters() {
		return parameters;
	}

	public void setParameters(Map<String, Object> parameters) {
		this.parameters = parameters;
	}

	public void setOrders(Collection<OrderColumn> orders) {
		this.orders = orders;
	}

	public Collection<OrderColumn> getOrders() {
		return orders;
	}
	
	public void getDefaultOrderFromFields(Class<?> cls) {
		Field[] fields = cls.getDeclaredFields();
		for(int x=0; x < fields.length; x++) {
			Field field = fields[x];
			boolean accessible = field.isAccessible();
			field.setAccessible(true);
			DefaultOrder defaultOrder = field.getAnnotation(DefaultOrder.class);
			if ( defaultOrder != null ) {
				OrderColumn oc = new OrderColumn();
				oc.setName(field.getName());
				oc.setAsc(defaultOrder.asc());
				orders.add(oc);
			}
			field.setAccessible(accessible);
		}
	}

}